home *** CD-ROM | disk | FTP | other *** search
/ HamCall (April 1991) / HAMCALL CD-ROM (Buckmaster)(April 1991).BIN / prgming / ctutor / chap11.txt < prev    next >
Text File  |  1990-10-14  |  28KB  |  642 lines

  1.  
  2.                                                     Chapter 11
  3.  
  4.                                          STRUCTURES AND UNIONS
  5.  
  6.  
  7.  
  8.  
  9. WHAT IS A STRUCTURE?
  10. ______________________________________________________________
  11.  
  12. A structure is a user defined data type.         =============
  13. Using a structure you have the ability to          STRUCT1.C
  14. define a new type of data considerably more      =============
  15. complex than the types we have been using.
  16. A structure is a combination of several different previously
  17. defined data types, including other structures we have
  18. defined.  A simple definition is, "a structure is a grouping
  19. of related data in a way convenient to the programmer or user
  20. of the program."  The best way to understand a structure is
  21. to look at an example, so if you will load and display
  22. STRUCT1.C, we will do just that.
  23.  
  24. The program begins with a structure definition.  The key word
  25. "struct" is followed by some simple variables between the
  26. braces, which are the components of the structure.  After the
  27. closing brace, you will find two variables listed, namely
  28. "boy", and "girl".  According to the definition of a
  29. structure, "boy" is now a variable composed of three elements,
  30. "initial", "age", and "grade".  Each of the three fields are
  31. associated with "boy", and each can store a variable of its
  32. respective type.  The variable "girl" is also a variable
  33. containing three fields with the same names as those of "boy"
  34. but are actually different variables.  We have therefore
  35. defined 6 simple variables.
  36.  
  37.  
  38. A SINGLE COMPOUND VARIABLE
  39. ______________________________________________________________
  40.  
  41. Lets examine the variable "boy" more closely.  As stated
  42. above, each of the three elements of "boy" are simple
  43. variables and can be used anywhere in a C program where a
  44. variable of their type can be used.  For example, the "age"
  45. element is an integer variable and can therefore be used
  46. anywhere in a C program where it is legal to use an integer
  47. variable, in calculations, as a counter, in I/O operations,
  48. etc.  We now have the problem of defining how to use the
  49. simple variable "age" which is a part of the compound variable
  50. "boy".  To do so we use both names with a decimal point
  51. between them with the major name first.  Thus "boy.age" is the
  52. complete variable name for the "age" field of "boy".  This
  53. construct can be used anywhere in a C program that it is
  54. desired to refer to this field.  In fact, it is illegal to use
  55. the name "boy" or "age" alone because they are only partial
  56. definitions of the complete field.  Alone, the names refer to
  57. nothing.  (Actually the name "boy" alone does have meaning
  58.  
  59.                                                           11-1
  60.  
  61.                             Chapter 11 - Structures and Unions
  62.  
  63. when used with some of the newest C compilers.  We will
  64. discuss this later.)
  65.  
  66.  
  67. ASSIGNING VALUES TO THE VARIABLES
  68. ______________________________________________________________
  69.  
  70. Using the above definition, we can assign a value to each of
  71. the three fields of "boy" and each of the three fields of
  72. "girl".  Note carefully that "boy.initial" is actually a
  73. "char" type variable, because it was assigned that in the
  74. structure, so it must be assigned a character of data.  In
  75. line 11, "boy.initial" is assigned the character 'R' in
  76. agreement with the above rules.  The remaining two fields of
  77. "boy" are assigned values in accordance with their respective
  78. types.  Finally the three fields of girl are assigned values
  79. but in a different order to illustrate that the order of
  80. assignment is not critical.
  81.  
  82.  
  83. HOW DO WE USE THE RESULTING DATA?
  84. ______________________________________________________________
  85.  
  86. Now that we have assigned values to the six simple variables,
  87. we can do anything we desire with them.  In order to keep this
  88. first example simple, we will simply print out the values to
  89. see if they really do exist as assigned.  If you carefully
  90. inspect the "printf" statements, you will see that there is
  91. nothing special about them.  The compound name of each
  92. variable is specified because that is the only valid name by
  93. which we can refer to these variables.
  94.  
  95. Structures are a very useful method of grouping data together
  96. in order to make a program easier to write and understand.
  97. This first example is too simple to give you even a hint of
  98. the value of using structures, but continue on through these
  99. lessons and eventually you will see the value of using
  100. structures.  Compile and run STRUCT1.C and observe the output.
  101.  
  102.  
  103. AN ARRAY OF STRUCTURES
  104. ______________________________________________________________
  105.  
  106. Load and display the next program named          =============
  107. STRUCT2.C.  This program contains the same         STRUCT2.C
  108. structure definition as before but this time     =============
  109. we define an array of 12 variables named
  110. "kids".  This program therefore contains 12 times 3 = 36
  111. simple variables, each of which can store one item of data
  112. provided that it is of the correct type.  We also define a
  113. simple variable named "index" for use in the "for" loops.
  114.  
  115.  
  116.  
  117.                                                           11-2
  118.  
  119.                             Chapter 11 - Structures and Unions
  120.  
  121. In order to assign each of the fields a value, we use a "for"
  122. loop and each pass through the loop results in assigning a
  123. value to three of the fields.  One pass through the loop
  124. assigns all of the values for one of the "kids".  This would
  125. not be a very useful way to assign data in a real situation,
  126. but a loop could read the data in from a file and store it in
  127. the correct fields.  You might consider this the crude
  128. beginning of a data base, which it is.
  129.  
  130. In the next few instructions of the program we assign new
  131. values to some of the fields to illustrate the method used to
  132. accomplish this. It should be self explanatory, so no
  133. additional comments will be given.
  134.  
  135.  
  136. A RECENT UPGRADE TO THE C LANGUAGE
  137. ______________________________________________________________
  138.  
  139. Most modern C compilers will allow you to copy an entire
  140. structure with one statement.  This is a fairly recent
  141. addition to the C language and will be a part of the ANSI
  142. standard when it is published, so you should feel free to use
  143. it with your C compiler if it is available.  Line 22 is an
  144. example of using a structure assignment.  In this statement,
  145. all 3 fields of kids[4] are copied into their respective
  146. fields of kids[10].
  147.  
  148.  
  149. WE FINALLY DISPLAY ALL OF THE RESULTS
  150. ______________________________________________________________
  151.  
  152. The last few statements contain a "for" loop in which all of
  153. the generated values are displayed in a formatted list.
  154. Compile and run the program to see if it does what you expect
  155. it to do.  You will need to remove line 22 if your compiler
  156. does not support structure assignments.
  157.  
  158.  
  159. USING POINTERS AND STRUCTURES TOGETHER
  160. ______________________________________________________________
  161.  
  162. Examine the file named STRUCT3.C for an          =============
  163. example of using pointers with structures.         STRUCT3.C
  164. This program is identical to the last program    =============
  165. except that it uses pointers for some of the
  166. operations.
  167.  
  168. The first difference shows up in the definition of variables
  169. following the structure definition.  In this program we define
  170. a pointer named "point" which is defined as a pointer that
  171. points to the structure.  It would be illegal to try to use
  172. this pointer to point to any other variable type.  There is
  173. a very definite reason for this restriction in C as we have
  174. alluded to earlier and will review in the next few paragraphs.
  175.  
  176.                                                           11-3
  177.  
  178.                             Chapter 11 - Structures and Unions
  179.  
  180. The next difference is in the "for" loop where we use the
  181. pointer for accessing the data fields.  Recall from chapter
  182. 8 of this tutorial that we said that the name of an array is
  183. actually a pointer to the first element of the array.  Since
  184. "kids" is a pointer variable that points to the first element
  185. of the array which is a structure, we can define "point" in
  186. terms of "kids".  The variable "kids" is a constant so it
  187. cannot be changed in value, but "point" is a pointer variable
  188. and can be assigned any value consistent with its being
  189. required to point to the structure.  If we assign the value
  190. of "kids" to "point" then it should be clear that it will
  191. point to the first element of the array, a structure
  192. containing three fields.
  193.  
  194.  
  195.  
  196. POINTER ARITHMETIC
  197. ______________________________________________________________
  198.  
  199. Adding 1 to "point" will now cause it to point to the second
  200. field of the array because of the way pointers are handled in
  201. C.  The system knows that the structure contains three
  202. variables and it knows how many memory elements are required
  203. to store the complete structure.  Therefore if we tell it to
  204. add one to the pointer, it will actually add the number of
  205. memory elements required to get to the next element of the
  206. array.  If, for example, we were to add 4 to the pointer, it
  207. would advance the value of the pointer 4 times the size of the
  208. structure, resulting in it pointing 4 elements farther along
  209. the array.  This is the reason a pointer cannot be used to
  210. point to any data type other than the one for which it was
  211. defined.
  212.  
  213. Now to return to the program displayed on your monitor.  It
  214. should be clear from the previous discussion that as we go
  215. through the loop, the pointer will point to the beginning of
  216. one of the array elements each time.  We can therefore use the
  217. pointer to reference the various elements of the structure.
  218. Referring to the elements of a structure with a pointer occurs
  219. so often in C that a special method of doing that was devised.
  220. Using "point->initial" is the same as using "(*point).initial"
  221. which is really the way we did it in the last two programs.
  222. Remember that *point is the stored data to which the pointer
  223. points and the construct should be clear.  The "->" is made
  224. up of the minus sign and the greater than sign.
  225.  
  226. Since the pointer points to the structure, we must once again
  227. define which of the elements we wish to refer to each time we
  228. use one of the elements of the structure.  There are, as we
  229. have seen, several different methods of referring to the
  230. members of the structure, and in the "for" loop used for
  231. output at the end of the program, we use three different
  232. methods.  This would be considered very poor programming
  233.  
  234.                                                           11-4
  235.  
  236.                             Chapter 11 - Structures and Unions
  237.  
  238. practice, but is done this way here to illustrate to you that
  239. they all lead to the same result.  This program will probably
  240. require some study on your part to fully understand, but it
  241. will be worth your time and effort to grasp these principles.
  242.  
  243. Lines 29 and 30 are two additional examples of structure
  244. assignment for your benefit.  Compile and run this program,
  245. and once again, if your compiler does not support structure
  246. assignment, you will need to remove lines 29 and 30.
  247.  
  248.  
  249.  
  250. NESTED AND NAMED STRUCTURES
  251. ______________________________________________________________
  252.  
  253. Examine the file named NESTED.C for an          ==============
  254. example of a nested structure.  The                NESTED.C
  255. structures we have seen so far have been very   ==============
  256. simple, although useful.  It is possible to
  257. define structures containing dozens and even hundreds or
  258. thousands of elements but it would be to the programmers
  259. advantage not to define all of the elements at one pass but
  260. rather to use a hierarchical structure of definition.  This
  261. will be illustrated with the program on your monitor.
  262.  
  263. The first structure contains three elements but is followed
  264. by no variable name.  We therefore have not defined any
  265. variables, only a structure, but since we have included a name
  266. at the beginning of the structure, the structure is named
  267. "person".  The name "person" can be used to refer to the
  268. structure but not to any variable of this structure type.  It
  269. is therefore a new type that we have defined, and we can use
  270. the new type in nearly the same way we use "int", "char", or
  271. any other types that exist in C.  The only restriction is that
  272. this new name must always be associated with the reserved word
  273. "struct".
  274.  
  275. The next structure definition contains three fields with the
  276. middle field being the previously defined structure which we
  277. named "person".  The variable which has the type of "person"
  278. is named "descrip".  So the new structure contains two simple
  279. variables, "grade" and a string named "lunch[25]", and the
  280. structure named "descrip".  Since "descrip" contains three
  281. variables, the new structure actually contains 5 variables.
  282. This structure is also given a name "alldat", which is another
  283. type definition.  Finally we define an array of 53 variables
  284. each with the structure defined by "alldat", and each with the
  285. name "student".  If that is clear, you will see that we have
  286. defined a total of 53 times 5 variables, each of which is
  287. capable of storing a value.
  288.  
  289.  
  290.  
  291.  
  292.                                                           11-5
  293.  
  294.                             Chapter 11 - Structures and Unions
  295.  
  296. TWO MORE VARIABLES
  297. ______________________________________________________________
  298.  
  299. Since we have a new type definition we can use it to define
  300. two more variables.  The variables "teacher" and "sub" are
  301. defined in line 16 to be variables of the type "alldat", so
  302. that each of these two variables contain 5 fields in which we
  303. can store data.
  304.  
  305.  
  306. NOW TO USE SOME OF THE FIELDS
  307. ______________________________________________________________
  308.  
  309. In the next five lines of the program, we will assign values
  310. to each of the fields of "teacher".  The first field is the
  311. "grade" field and is handled just like the other structures
  312. we have studied because it is not part of the nested
  313. structure.  Next we wish to assign a value to her age which
  314. is part of the nested structure.  To address this field we
  315. start with the variable name "teacher" to which we append the
  316. name of the group "descrip", and then we must define which
  317. field of the nested structure we are interested in, so we
  318. append the name "age".  The teachers status is handled in
  319. exactly the same manner as her age, but the last two fields
  320. are assigned strings using the string copy "strcpy" function
  321. which must be used for string assignment.  Notice that the
  322. variable names in the "strcpy" function are still variable
  323. names even though they are made up of several parts each.
  324.  
  325. The variable "sub" is assigned nonsense values in much the
  326. same way, but in a different order since they do not have to
  327. occur in any required order.  Finally, a few of the "student"
  328. variables are assigned values for illustrative purposes and
  329. the program ends.  None of the values are printed for
  330. illustration since several were printed in the last examples.
  331.  
  332. Compile and run this program, but when you run it, you may get
  333. a "stack overflow" error.  C uses its own internal stack to
  334. store the automatic variables on, but most C compilers use
  335. only a 2048 byte stack as a default.  This program requires
  336. more than that for the defined structures so it will be
  337. necessary for you to increase the stack size.  Consult your
  338. compiler documentation for details concerning the method of
  339. increasing the stack size.  There is no standard way to do
  340. this.  There is another way around this problem, and that is
  341. to move the structure and variable definitions outside of the
  342. program where they will be external variables and therefore
  343. static.  The result is that they will not be kept on the
  344. internal stack and the stack will not overflow.  It would be
  345. good for you to try both methods of fixing this problem.
  346.  
  347.  
  348.  
  349.  
  350.                                                           11-6
  351.  
  352.                             Chapter 11 - Structures and Unions
  353.  
  354. MORE ABOUT STRUCTURES
  355. ______________________________________________________________
  356.  
  357. It is possible to continue nesting structures until you get
  358. totally confused.  If you define them properly, the computer
  359. will not get confused because there is no stated limit as to
  360. how many levels of nesting are allowed.  There is probably a
  361. practical limit of three beyond which you will get confused,
  362. but the language has no limit.  In addition to nesting, you
  363. can include as many structures as you desire in any level of
  364. structures, such as defining another structure prior to
  365. "alldat" and using it in "alldat" in addition to using
  366. "person".  The structure named "person" could be included in
  367. "alldat" two or more times if desired, as could pointers to
  368. it.
  369.  
  370. Structures can contain arrays of other structures which in
  371. turn can contain arrays of simple types or other structures.
  372. It can go on and on until you lose all reason to continue.
  373. I am only trying to illustrate to you that structures are very
  374. valuable and you will find them great aids to programming if
  375. you use them wisely.  Be conservative at first, and get bolder
  376. as you gain experience.
  377.  
  378. More complex structures will not be illustrated here, but you
  379. will find examples of additional structures in the example
  380. programs included in the last chapter of this tutorial.  For
  381. example, see the "#include" file "STRUCT.DEF".
  382.  
  383.  
  384. WHAT ARE UNIONS?
  385. ______________________________________________________________
  386.  
  387. Examine the file named UNION1.C for an          ==============
  388. example of a union.  Simply stated, a union        UNION1.C
  389. allows you a way to look at the same data       ==============
  390. with different types, or to use the same data
  391. with different names.
  392.  
  393. In this example we have two elements to the union, the first
  394. part being the integer named "value", which is stored as a two
  395. byte variable somewhere in the computers memory.  The second
  396. element is made up of two character variables named "first"
  397. and "second".  These two variables are stored in the same
  398. storage locations that "value" is stored in, because that is
  399. what a union does.  A union allows you to store different
  400. types of data in the same physical storage locations.  In this
  401. case, you could put an integer number in "value", then
  402. retrieve it in its two halves by getting each half using the
  403. two names "first" and "second".  This technique is often used
  404. to pack data bytes together when you are, for example,
  405. combining bytes to be used in the registers of the
  406. microprocessor.
  407.  
  408.                                                           11-7
  409.  
  410.                             Chapter 11 - Structures and Unions
  411.  
  412. Accessing the fields of the union are very similar to
  413. accessing the fields of a structure and will be left to you
  414. to determine by studying the example.
  415.  
  416. One additional note must be given here about the program.
  417. When it is run using some C compilers, the data will be
  418. displayed with two leading f's due to the hexadecimal output
  419. promoting the char type variables to int and extending the
  420. sign bit to the left.  Converting the char type data fields
  421. to int type fields prior to display should remove the leading
  422. f's from your display.  This will involve defining two new
  423. int type variables and assigning the char type variables to
  424. them.  This will be left as an exercise for you.  Note that
  425. the same problem will come up in a few of the later files
  426. also.
  427.  
  428. Compile and run this program and observe that the data is read
  429. out as an "int" and as two "char" variables.  The "char"
  430. variables may be reversed in order because of the way an "int"
  431. variable is stored internally in your computer.  If your
  432. system reverses these variables, don't worry about it.  It is
  433. not a problem but it can be a very interesting area of study
  434. if you are so inclined.
  435.  
  436.  
  437. ANOTHER UNION EXAMPLE
  438. ______________________________________________________________
  439.  
  440. Load and display the file named UNION2.C for    ==============
  441. another example of a union, one which is much      UNION2.C
  442. more common.  Suppose you wished to build a     ==============
  443. large database including information on many
  444. types of vehicles.  It would be silly to include the number
  445. of propellers on a car, or the number of tires on a boat.  In
  446. order to keep all pertinent data, however, you would need
  447. those data points for their proper types of vehicles.  In
  448. order to build an efficient data base, you would need several
  449. different types of data for each vehicle, some of which would
  450. be common, and some of which would be different.  That is
  451. exactly what we are doing in the example program on your
  452. monitor.
  453.  
  454. In this program, we will define a complete structure, then
  455. decide which of the various types can go into it.  We will
  456. start at the top and work our way down.  First, we define a
  457. few constants with the #defines, and begin the program itself.
  458. We define a structure named "automobile" containing several
  459. fields which you should have no trouble recognizing, but we
  460. define no variables at this time.
  461.  
  462.  
  463.  
  464.  
  465.  
  466.                                                           11-8
  467.  
  468.                             Chapter 11 - Structures and Unions
  469.  
  470. A NEW CONCEPT, THE TYPEDEF
  471. ______________________________________________________________
  472.  
  473. Next we define a new type of data with a "typedef".  This
  474. defines a complete new type that can be used in the same way
  475. that "int" or "char" can be used.  Notice that the structure
  476. has no name, but at the end where there would normally be a
  477. variable name there is the name "BOATDEF".  We now have a new
  478. type, "BOATDEF", that can be used to define a structure
  479. anyplace we would like to.  Notice that this does not define
  480. any variables, only a new type definition.  Capitalizing the
  481. name is a personal preference only and is not a C standard.
  482. It makes the "typedef" look different from a variable name.
  483.  
  484. We finally come to the big structure that defines our data
  485. using the building blocks already defined above.  The
  486. structure is composed of 5 parts, two simple variables named
  487. "vehicle" and "weight", followed by the union, and finally the
  488. last two simple variables named "value" and "owner".  Of
  489. course the union is what we need to look at carefully here,
  490. so focus on it for the moment.  You will notice that it is
  491. composed of four parts, the first part being the variable
  492. "car" which is a structure that we defined previously.  The
  493. second part is a variable named "boat" which is a structure
  494. of the type "BOATDEF" previously defined.  The third part of
  495. the union is the variable "airplane" which is a structure
  496. defined in place in the union.  Finally we come to the last
  497. part of the union, the variable named "ship" which is another
  498. structure of the type "BOATDEF".
  499.  
  500. I hope it is obvious to you that all four could have been
  501. defined in any of the three ways shown, but the three
  502. different methods were used to show you that any could be
  503. used.  In practice, the clearest definition would probably
  504. have occurred by using the "typedef" for each of the parts.
  505.  
  506.  
  507. WHAT DO WE HAVE NOW?
  508. ______________________________________________________________
  509.  
  510. We now have a structure that can be used to store any of four
  511. different kinds of data structures.  The size of every record
  512. will be the size of that record containing the largest union.
  513. In this case part 1 is the largest union because it is
  514. composed of three integers, the others being composed of an
  515. integer and a character each.  The first member of this union
  516. would therefore determine the size of all structures of this
  517. type.  The resulting structure can be used to store any of the
  518. four types of data, but it is up to the programmer to keep
  519. track of what is stored in each variable of this type.  The
  520. variable "vehicle" was designed into this structure to keep
  521. track of the type of vehicle stored here.  The four defines
  522. at the top of the page were designed to be used as indicators
  523. to be stored in the variable "vehicle".
  524.  
  525.                                                           11-9
  526.  
  527.                             Chapter 11 - Structures and Unions
  528.  
  529. A few examples of how to use the resulting structure are given
  530. in the next few lines of the program.  Some of the variables
  531. are defined and a few of them are printed out for illustrative
  532. purposes.
  533.  
  534. The union is not used too frequently, and almost never by
  535. beginning programmers.  You will encounter it occasionally so
  536. it is worth your effort to at least know what it is.  You do
  537. not need to know the details of it at this time, so don't
  538. spend too much time studying it.  When you do have a need for
  539. a variant structure, a union, you can learn it at that time.
  540. For your own benefit, however, do not slight the structure.
  541. You should use the structure often.
  542.  
  543.  
  544.  
  545. WHAT IS A BITFIELD?
  546. ______________________________________________________________
  547.  
  548. Load and display the program named BITFIELD.C   ==============
  549. for an example of how to define and use a         BITFIELD.C
  550. bitfield, a relatively new addition to the      ==============
  551. programming language C.  In this program, we
  552. have a union made up of a single "int" type variable in line
  553. 5 and the structure defined in lines 6 through 10.  The
  554. structure is composed of three bitfields named "x", "y", and
  555. "z".  The variable named "x" is only one bit wide, the
  556. variable "y" is two bits wide and adjacent to the variable
  557. "x", and the variable "z" is two bits wide and adjacent to
  558. "y".  Moreover, because the union causes the bits to be stored
  559. in the same memory location as the variable "index", the
  560. variable "x" is the least significant bit of the variable
  561. "index", "y" is the next two bits, and "z" is the next two.
  562.  
  563. Compile and run the program and you will see that as the
  564. variable "index" is incremented by 1 each time you will see
  565. the bitfields of the union counting due to their respective
  566. locations within the "int" definition.  Note that your
  567. compiler may not support the bitfield since it is a relatively
  568. new construct to the C programming language.
  569.  
  570. One thing must be pointed out, the bitfields must be defined
  571. as parts of an "unsigned int" or your compiler will issue an
  572. error message.
  573.  
  574.  
  575.  
  576. WHAT IS THE BITFIELD GOOD FOR?
  577. ______________________________________________________________
  578.  
  579. The bitfield is very useful if you have a lot of data to
  580. separate into separate bits or groups of bits.  Many systems
  581. use some sort of a packed format to get lots of data stored
  582.  
  583.                                                          11-10
  584.  
  585.                              Chapter 11 - Structures and Unions
  586.  
  587. in a few bytes.  Your imagination is your only limitation to
  588. use of this feature of C.
  589.  
  590.  
  591. PROGRAMMING EXERCISES
  592. ______________________________________________________________
  593.  
  594. 1.   Define a named structure  containing a string field for
  595.      a name, an integer for feet, and another for arms.  Use
  596.      the new type to define an array of about 6 items.  Fill
  597.      the fields with data and print them out as follows.
  598.  
  599.        A human being has 2 legs and 2 arms.
  600.        A dog has 4 legs and 0 arms.
  601.        A television set has 4 legs and 0 arms.
  602.        A chair has 4 legs and 2 arms.
  603.         etc.
  604.  
  605. 2.   Rewrite exercise 1 using a pointer to print the data out.
  606.  
  607.  
  608.  
  609.  
  610.  
  611.  
  612.  
  613.  
  614.  
  615.  
  616.  
  617.  
  618.  
  619.  
  620.  
  621.  
  622.  
  623.  
  624.  
  625.  
  626.  
  627.  
  628.  
  629.  
  630.  
  631.  
  632.  
  633.  
  634.  
  635.  
  636.  
  637.  
  638.  
  639.  
  640.                                                           11-11
  641.  
  642.